package com.jftone.bh.app.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.jftone.bh.app.model.SysAdmin;
import com.jftone.bh.app.model.SysAdminRole;
import com.jftone.bh.app.service.AdminService;
import org.apache.log4j.Logger;
import org.jftone.annotation.Autowired;
import org.jftone.annotation.Controller;
import org.jftone.exception.ActionException;
import org.jftone.exception.ComponentException;
import org.jftone.util.DataMap;
import org.jftone.util.IData;
import org.jftone.util.IPv4Util;
import org.jftone.util.StringUtil;


@Controller(mapping="/sysAdminAction")
public class SysAdminAction extends BaseAction {

	private Logger logger = Logger.getLogger(SysAdminAction.class);
	
	@Autowired
	private AdminService service;
	
	public void query() throws ActionException{
		try {
			List<SysAdmin> list  = service.querySysAdmin(null, getPage());
			this.putRenderInfo("sysAdminList", list);
			//设置功能按钮
			setMenuFuncDerictive();
			setPageDerictive();
		} catch (Exception e) {
			logger.error("查询管理员信息错误"+e.getMessage(), e);
			throw new ActionException("查询管理员信息错误"+e.getMessage(), e);
		}
		this.render("sys_admin.html");
	}
	
	public void add() throws ActionException{
		List<IData<String, Object>> roles = new ArrayList<IData<String, Object>>();
		try {
			List<IData<String, Object>> list  = service.querySysRole();
			for(IData<String, Object> d : list){
				IData<String, Object> tmp = new DataMap<String, Object>();
				tmp.put("checked", false);
				tmp.put("roleName", d.getString("ROLE_NAME"));
				tmp.put("roleCode", d.getString("ROLE_CODE"));
				tmp.put("roleLevel", d.getString("ROLE_LEVEL"));
				roles.add(tmp);
			}
			SysAdmin admin = new SysAdmin();
			admin.setLocked((short)0);
			this.putRenderInfo("admin", admin);
			this.putRenderInfo("roles", roles);
		} catch (Exception e) {
			logger.error("加载管理员角色信息错误"+e.getMessage(), e);
			throw new ActionException("加载管理员角色信息错误"+e.getMessage(), e);
		}
		this.render("sys_admin_form.html");
	}

	public void edit() throws ActionException{
		IData<String, Object> data = getData();
		String dataId = data.getString("dataId", "");
		if(StringUtil.isBlank(dataId) || !StringUtil.isNumber(dataId)){
			this.alertMsg("参数传值错误");
			return;
		}
		try {
			IData<String, Object> inData = new DataMap<String, Object>();
			inData.put("id", Integer.parseInt(dataId));
			SysAdmin admin = service.getSysAdmin(inData);
			
			inData.clear();
			inData.put("userNo", admin.getAdminUser());
			List<SysAdminRole> sarList  = service.querySysAdminRole(inData);
			IData<String, String> sarMap = new DataMap<String, String>();
			for(SysAdminRole adminRole : sarList){
				sarMap.put(adminRole.getRoleCode(), adminRole.getRoleCode());
			}
			List<IData<String, Object>> list  = service.querySysRole();
			List<IData<String, Object>> roles = new ArrayList<IData<String, Object>>();
			String keyCode = null;
			for(IData<String, Object> d : list){
				keyCode = d.getString("ROLE_CODE");
				IData<String, Object> tmp = new DataMap<String, Object>();
				tmp.put("checked", sarMap.containsKey(keyCode));
				tmp.put("roleName", d.getString("ROLE_NAME"));
				tmp.put("roleCode", keyCode);
				tmp.put("roleLevel", d.getString("ROLE_LEVEL"));
				roles.add(tmp);
			}

			this.putRenderInfo("admin", admin);
			this.putRenderInfo("roles", roles);
		} catch (Exception e) {
			logger.error("加载管理员角色信息错误"+e.getMessage(), e);
			throw new ActionException("加载管理员角色信息错误"+e.getMessage(), e);
		}
		this.render("sys_admin_form.html");
	}

	public void save() throws ActionException{
		boolean updateFlag = false;
		IData<String, Object> data = getData();
		String adminId = data.getString("adminId");
		String adminUser = data.getString("adminUser");
		Date curTime = new Date();
		try {
			SysAdmin admin = new SysAdmin();
			if(!StringUtil.isBlank(adminId) && StringUtil.isNumber(adminId)){
				admin.setId(Integer.parseInt(adminId));
				updateFlag = true;
			}else{
				String password = data.getString("password");
				String confirmPwd = data.getString("confirmPwd");
				if(StringUtil.isBlank(password) || StringUtil.isBlank(confirmPwd)
						|| !password.equals(confirmPwd)){
					this.alertMsg("确认密码和登录密码不相同！");
					return;
				}
				admin.setPassword(password);
				admin.setCreateTime(curTime);
				admin.setLoginTime(curTime);
				admin.setLoginIp(IPv4Util.getIpAddr(getRequest()));
			}
			admin.setAdminUser(adminUser);
			admin.setUserName(data.getString("userName"));
			admin.setMobile(data.getString("mobile"));
			admin.setEmail(data.getString("email"));
			admin.setLocked(Short.parseShort(data.getString("locked")));
			admin.setRemark(data.getString("remark"));
			
			List<SysAdminRole> adminRoles  = new ArrayList<SysAdminRole>();
			String roleCode = data.getString("roleCode", "");
			if(StringUtil.isBlank(roleCode)){
				this.alertMsg("请至少选择一个角色！");
				return;
			}
			String[] tmps = roleCode.split(",");
			for(String code : tmps){
				SysAdminRole adminRole = new SysAdminRole();
				adminRole.setUserNo(adminUser);
				adminRole.setRoleCode(code);
				adminRoles.add(adminRole);
			}
			
			if(service.saveAdmin(admin, adminRoles)==1){
				this.alertMsg("当前登录用户已经存在，请修改!");
				return;
			}
			this.showMsg("系统管理员"+(updateFlag? "保存" : "新增")+"成功", "?method=query");
		} catch (ComponentException e) {
			logger.error("保存系统菜单节点信息错误："+e.getMessage(), e);
			throw new ActionException("保存系统菜单节点信息错误", e);
		}
	}
	
	public void delete() throws ActionException{
		IData<String, Object> data = getData();
		String dataId = data.getString("dataId", "");
		if(StringUtil.isBlank(dataId) || !StringUtil.isNumber(dataId)){
			this.alertMsg("参数传值错误");
			return;
		}
		try {
			int resultCode = service.deleteAdmin(Integer.parseInt(dataId));
			if(resultCode == 1){
				this.alertMsg("数据错误，请刷新后重试");
				return;
			}
			this.showMsg("系统管理员删除成功", "?method=query");
		} catch (ComponentException e) {
			logger.error("删除系统管理员数据错误"+e.getMessage(), e);
			throw new ActionException("删除系统管理员数据错误"+e.getMessage(), e);
		}
		
	}
	
	public void modifyKey() throws ActionException{
		IData<String, Object> data = getData();
		String dataId = data.getString("dataId", "");
		if(StringUtil.isBlank(dataId) || !StringUtil.isNumber(dataId)){
			this.alertMsg("参数传值错误");
			return;
		}
		try {
			IData<String, Object> inData = new DataMap<String, Object>();
			inData.put("id", Integer.parseInt(dataId));
			SysAdmin admin = service.getSysAdmin(inData);
			this.putRenderInfo("admin", admin);
			this.render("sys_admin_pwd.html");
		} catch (Exception e) {
			logger.error("加载系统管理员数据错误"+e.getMessage(), e);
			throw new ActionException("加载系统管理员数据错误"+e.getMessage(), e);
		}
	}
	
	public void saveKey() throws ActionException{
		IData<String, Object> data = getData();
		String adminId = data.getString("adminId");
		if(StringUtil.isBlank(adminId) || !StringUtil.isNumber(adminId)){
			this.alertMsg("参数传值错误");
			return;
		}
		try {
			SysAdmin admin = new SysAdmin();
			String password = data.getString("password");
			String confirmPwd = data.getString("confirmPwd");
			if(StringUtil.isBlank(password) || StringUtil.isBlank(confirmPwd)
					|| !password.equals(confirmPwd)){
				this.alertMsg("确认密码和登录密码不相同！");
				return;
			}
			admin.setPassword(password);
			admin.setId(Integer.parseInt(adminId));
			service.updateAdminPass(admin);
			this.showMsg("系统管理员密码修改成功", "?method=query");
		} catch (Exception e) {
			logger.error("修改管理员密码信息错误："+e.getMessage(), e);
			throw new ActionException("修改管理员密码信息错误", e);
		}
	}
}
